package designpattern;

/**
 * 单例模式
 *
 * @author: fengpeng
 * @date: 2019/2/19  上午11:28
 */
public class Singleton {
    public static void main(String[] args){
        LazySingleton lazySingleton1 = LazySingleton.getInstance();
        LazySingleton lazySingleton2 = LazySingleton.getInstance();
        System.out.println("饿汉式单例测试："+(lazySingleton1 == lazySingleton2));
        System.out.println("-------------------------------------------------");
        HungerSingleton hungerSingleton1 = HungerSingleton.getInstance();
        HungerSingleton hungerSingleton2 = HungerSingleton.getInstance();
        System.out.println("懒汉式单例测试："+(hungerSingleton1 == hungerSingleton2));
    }
}

/**
 * 懒汉式单例（只有用时才会创建）
 */
class LazySingleton{
    private LazySingleton(){
        //啥都不做，同时避免别人创建
    }
    private static volatile LazySingleton lazySingleton = null;

    /**
     * 提供公共的方法(注意线程安全)
     *
     * @return 单例对象
     */
    public static LazySingleton getInstance(){
        if (lazySingleton == null){
            synchronized (LazySingleton.class){
                if (lazySingleton == null){
                    lazySingleton = new LazySingleton();
                }
            }
        }
        return lazySingleton;
    }
}
/**
 * 饿汉式（启动服务时就会创建）
 */
class HungerSingleton{

    private HungerSingleton(){}

    private static  HungerSingleton hungerSingleton = new HungerSingleton();

    public static HungerSingleton getInstance(){
        return hungerSingleton;
    }


}
